package org.sy.lab.多线程基础._2_同步._1_synchronized._2_使用条件;

/**
 * 仓库
 */
public class Storage {
	
	private int max = 100;
	private int num = 0;
	
	public synchronized void add(int n) {
		
		while(num + n > max) {
			try {
				System.out.println(Thread.currentThread().getName() + "  要增加：" + n + "  仓库存量：" + num + "  无法加入，进入等待");
				wait();
				System.out.println(Thread.currentThread().getName() + "  被唤醒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		num += n;
		System.out.println(Thread.currentThread().getName() + "  已增加：" + n + "  现仓库存量：" + num);
		notifyAll();
	}
	
	public synchronized void subtract(int n) {
		
		while(num - n < 0) {
			try {
				System.out.println(Thread.currentThread().getName() + "  要取出：" + n + "  仓库存量：" + num + "  无法取出，进入等待");
				wait();
				System.out.println(Thread.currentThread().getName() + "  被唤醒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		num -= n;
		System.out.println(Thread.currentThread().getName() + "  已取出：" + n + "  现仓库存量：" + num);
		notifyAll();
	}
	
	public int getNum() {
		return num;
	}
}
